import numpy as np
import cv2
import os
import pickle
import random
from tqdm import tqdm
from .build import DATASET_OUTPUT_DIR, DATASET_CONFIG_DIR, DATASET_REGISTRY, DATASET_INFO_REGISTRY
from .utils import get_dataset_info_cfg, setup_dataset_info, convert_to_one_category, map_category, get_plugin_annotations

DATASET = 'LSI'
DATASET_BASE_DIR = 'dataset/LSI'


CLASSES_LIST = ['person', 'car']
CLASSES_INDEX = dict()
for i, class_name in enumerate(CLASSES_LIST):
    CLASSES_INDEX[class_name] = i
FAKE_CLASSES_LIST = ['person', 'car']

map_dict = {
    0: 0,
    1: 1,
}

def get_LSI_dicts(DATASET_BASE_DIR, image_set_name):
    dataset_dicts = []

    annotations_dir = os.path.join(DATASET_BASE_DIR, image_set_name, 'annotations')
    for annotation_file in os.listdir(annotations_dir):
        annotation_full_path = os.path.join(annotations_dir, annotation_file)

        lines = None
        with open(annotation_full_path, 'r') as f:
            lines = f.readlines()
            
        image_filename = lines[2].split('"')[1].strip()
        image_size = [int(item.strip()) for item in lines[3].split(':')[-1].split('x')]
        objects_count = int(lines[5].split(':')[-1].split('{')[0].strip())

        objects_list = []
        # for each object
        for i in range(objects_count):
            start_line = 10 + 4 * i
            label = lines[start_line + 1].split(':')[0].split('"')[1]
            bounding_box = lines[start_line+2].split(':')[-1].replace('(', ' ').replace(')', ' ').replace(',', ' ').replace('-', ' ').strip().split()
            bounding_box = [float(item.strip()) for item in bounding_box]  # 必须是[float]否则会报错
            
            object_dict = {
                'label': label,
                'bounding_box': bounding_box
            }
            objects_list.append(object_dict)

        # to uniform interface
        objects = []
        for object in objects_list:
            object_dict = {
                'bbox': object['bounding_box'],
                'category_id': 0 # this dataset has only one category 'person'
            }
            objects.append(object_dict)
        
        record = {
            'file_name': os.path.join(DATASET_BASE_DIR, image_filename),
            'image_id': annotation_file[:-4],
            'annotations': objects,
            'params': {
                'height': image_size[0],
                'width': image_size[1],
            }
        }
        dataset_dicts.append(record)

    return dataset_dicts


def crop_dataset_dicts(dataset_dicts, size):
    """ size: (w, h) """
    random.seed(0)
    new_dataset_dicts = []
    for dataset_dict in dataset_dicts:
        h, w = dataset_dict['params']['height'], dataset_dict['params']['width']
        new_w, new_h = size
        x = int(random.random() * (w - new_w))
        y = int(random.random() * (h - new_h))

        clamp = lambda x, lower, upper: min(max(x, lower), upper)
        
        new_objects = []
        for obj in dataset_dict['annotations']:
            inter_w = max(min(x+new_w, obj['bbox'][2]) - max(x, obj['bbox'][0]), 0)
            inter_h = max(min(y+new_h, obj['bbox'][3]) - max(y, obj['bbox'][1]), 0)
            inter_area_ratio = inter_h * inter_w / ((obj['bbox'][3] - obj['bbox'][1]) * (obj['bbox'][2] - obj['bbox'][0]))
            if inter_area_ratio < 0.5:
                continue

            obj['bbox'][0] = clamp(obj['bbox'][0] - x, 0, new_w)
            obj['bbox'][1] = clamp(obj['bbox'][1] - y, 0, new_h)
            obj['bbox'][2] = clamp(obj['bbox'][2] - x, 0, new_w)
            obj['bbox'][3] = clamp(obj['bbox'][3] - y, 0, new_h)
            obj['bbox'] = [float(i) for i in obj['bbox']]
            new_objects.append(obj)
        dataset_dict['annotations'] = new_objects
        dataset_dict['params']['height'] = new_h
        dataset_dict['params']['width'] = new_w
        dataset_dict['params']['crop'] = [x, y, x+new_w, y+new_h]
        new_dataset_dicts.append(dataset_dict)
    return new_dataset_dicts


def remove_empty(dataset_dicts):
    dataset_dicts = [dataset_dict for dataset_dict in dataset_dicts if len(dataset_dict['annotations']) > 0]
    return dataset_dicts


def add_plugin_annotations(dataset_dicts, plugin_annotations_file):
    annotations_dict = get_plugin_annotations(plugin_annotations_file)
    for i in range(len(dataset_dicts)):
        filename = dataset_dicts[i]['file_name']
        if filename in annotations_dict:
            dataset_dicts[i]['annotations'] += annotations_dict[filename]
    return dataset_dicts

def remove_plugin_annotations(dataset_dicts, plugin_annotations_file):
    annotations_dict = get_plugin_annotations(plugin_annotations_file)
    new_dataset_dicts = []
    for dataset_dict in dataset_dicts:
        filename = dataset_dict['file_name']
        if not (filename in annotations_dict and len(annotations_dict[filename]) > 0):
            new_dataset_dicts.append(dataset_dict)
    return new_dataset_dicts

def bind_dataset_type(dataset_dicts, dataset_type):
    for i in range(len(dataset_dicts)):
        dataset_dicts[i]['params']['dataset_type'] = dataset_type
    return dataset_dicts

def get_dataset_dicts(dataset_name, **kwargs):
    available_set = set(['sep', 'crop', 'remove_empty', 'add_plugin', 'remove_plugin', 'bind_dataset_type'])
    assert set(kwargs.keys()).issubset(available_set), 'Invalid kwargs'

    content = ''
    if 'crop' in kwargs:
        content += '-[crop]-' + '-'.join([str(i) for i in kwargs['crop']['size']])
    if 'remove_empty' in kwargs:
        content += '-[remove_empty]'
    if 'add_plugin' in kwargs:
        content += '-[add_plu]-{}'.format(hashlib.blake2b(bytes(kwargs['add_plugin']['file'], encoding='utf-8'), digest_size=2).hexdigest())
    if 'remove_plugin' in kwargs:
        content += '-[rm_plu]-{}'.format(hashlib.blake2b(bytes(kwargs['remove_plugin']['file'], encoding='utf-8'), digest_size=2).hexdigest())
    if 'bind_dataset_type' in kwargs:
        content += '-[bdt]-' + str(kwargs['bind_dataset_type']['dataset_type'])
    pickle_file_name = os.path.join(DATASET_OUTPUT_DIR, DATASET + '-' + dataset_name + content + '-dataset.pkl')
    dataset_dicts = None
    if os.path.exists(pickle_file_name):
        with open(pickle_file_name, 'rb') as f:
            dataset_dicts = pickle.load(f)
    else:
        if 'bind_dataset_type' in kwargs:
            params = kwargs.pop('bind_dataset_type')
            dataset_dicts = get_dataset_dicts(dataset_name, **kwargs)
            dataset_dicts = bind_dataset_type(dataset_dicts, params['dataset_type'])
        elif 'remove_empty' in kwargs:
            kwargs.pop('remove_empty')
            dataset_dicts = get_dataset_dicts(dataset_name, **kwargs)
            dataset_dicts = remove_empty(dataset_dicts)
        elif 'crop' in kwargs:
            params = kwargs.pop('crop')
            dataset_dicts = get_dataset_dicts(dataset_name, **kwargs)
            dataset_dicts = crop_dataset_dicts(dataset_dicts, params['size'])
        elif 'add_plugin' in kwargs:
            params = kwargs.pop('add_plugin')
            dataset_dicts = get_dataset_dicts(dataset_name, **kwargs)
            dataset_dicts = add_plugin_annotations(dataset_dicts, params['file'])
        elif 'remove_plugin' in kwargs:
            params = kwargs.pop('remove_plugin')
            dataset_dicts = get_dataset_dicts(dataset_name, **kwargs)
            dataset_dicts = remove_plugin_annotations(dataset_dicts, params['file'])
        else:
            assert len(kwargs) == 0
            dataset_dicts = get_LSI_dicts(DATASET_BASE_DIR, dataset_name)
        os.makedirs(os.path.dirname(pickle_file_name), exist_ok=True)
        with open(pickle_file_name, 'wb') as f:
            pickle.dump(dataset_dicts, f)
    return dataset_dicts

dataset_name_train = 'Train'
dataset_name_test = 'Test'

DATASET_INFO_REGISTRY.register(DATASET, get_dataset_info_cfg(os.path.join(DATASET_CONFIG_DIR, 'LSI.yaml')))
DATASET_INFO_REGISTRY.register(DATASET+'-remove-empty', get_dataset_info_cfg(os.path.join(DATASET_CONFIG_DIR, 'LSI.yaml')))
DATASET_INFO_REGISTRY.register(DATASET+'-remove-empty-t0', get_dataset_info_cfg(os.path.join(DATASET_CONFIG_DIR, 'LSI.yaml')))
DATASET_INFO_REGISTRY.register(DATASET+'-add-plugin-remove-empty', get_dataset_info_cfg(os.path.join(DATASET_CONFIG_DIR, 'LSI.yaml')))
DATASET_INFO_REGISTRY.register(DATASET+'-rm-plugin-remove-empty', get_dataset_info_cfg(os.path.join(DATASET_CONFIG_DIR, 'LSI.yaml')))

for postfix, kwargs in {
        '': {},
        '-remove-empty': {
            'remove_empty': None
        },
        '-remove-empty-t0': {
            'remove_empty': None,
            'bind_dataset_type': {
                'dataset_type': 0,
            },
        },
        '-add-plugin-remove-empty': {
            'remove_empty': None,
            'add_plugin': {
                'file': 'dataset/LSI-plugin-annotations.txt'
            },
        },
        '-rm-plugin-remove-empty': {
            'remove_empty': None,
            'remove_plugin': {
                'file': 'dataset/LSI-plugin-annotations.txt'
            },
        },
    }.items():
    dataset_full_name = DATASET + postfix
    
    DATASET_REGISTRY.register(dataset_full_name +'-train', lambda dataset_name=dataset_name_train, kwargs=kwargs, dataset_info=DATASET_INFO_REGISTRY.get(dataset_full_name): setup_dataset_info(map_category(get_dataset_dicts(dataset_name, **kwargs), map_dict), dataset_info))
    DATASET_REGISTRY.register(dataset_full_name +'-test', lambda dataset_name=dataset_name_test, kwargs=kwargs, dataset_info=DATASET_INFO_REGISTRY.get(dataset_full_name): setup_dataset_info(map_category(get_dataset_dicts(dataset_name, **kwargs), map_dict), dataset_info))

